package com.luoxin.servicemap.remote;

import com.alibaba.fastjson.JSONObject;
import com.luoxin.internalcommon.constant.AmapConfigConstants;
import com.luoxin.internalcommon.dto.ResponseResult;
import com.luoxin.internalcommon.response.TrackResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service
public class TrackClient {
    @Value("${amap.key}")
    private String mapKey;
    @Value("${amap.sid}")
    private String sid;

    @Autowired
    private RestTemplate restTemplate;

    public ResponseResult<TrackResponse> addTrack(String tid) {
        StringBuilder url = new StringBuilder();
        url.append(AmapConfigConstants.TRACK_ADD);
        url.append("?");
        url.append("key="+mapKey);
        url.append("&");
        url.append("sid="+sid);
        url.append("&");
        url.append("tid="+tid);

        ResponseEntity<String> forEntity = restTemplate.postForEntity(url.toString(), null, String.class);
        String body = forEntity.getBody();
        log.info("高德地图创建轨迹结果:{}", body);
        JSONObject result = JSONObject.parseObject(body);
        String errcode = result.getString("errcode");
        if (!"10000".equals(errcode)){
            String errmsg = result.getString("errmsg");
            return ResponseResult.fail(Integer.valueOf(errcode), errmsg);
        }
        JSONObject data = result.getJSONObject("data");
        String trid = data.getString("trid");
        String trname = data.getString("trname");
        TrackResponse trackResponse = new TrackResponse();
        trackResponse.setTrid(trid);
        trackResponse.setTrname(trname);
        return ResponseResult.success(trackResponse);
    }


    /**
     * 删除轨迹
     * @param tid
     * @param trid
     * @return
     */
    public ResponseResult deleteTrack(String tid, String trid) {
        StringBuilder url = new StringBuilder();
        url.append(AmapConfigConstants.TRACK_DELETE);
        url.append("?");
        url.append("key="+mapKey);
        url.append("&");
        url.append("sid="+sid);
        url.append("&");
        url.append("tid="+tid);
        url.append("&");
        url.append("trid="+trid);

        ResponseEntity<String> forEntity = restTemplate.postForEntity(url.toString(), null, String.class);
        String body = forEntity.getBody();
        log.info("高德地图删除轨迹结果:{}", body);
        JSONObject result = JSONObject.parseObject(body);
        String errcode = result.getString("errcode");
        if (!"10000".equals(errcode)){
            String errmsg = result.getString("errmsg");
            return ResponseResult.fail(Integer.valueOf(errcode), errmsg);
        }
        return ResponseResult.success();
    }
}
